import {useDispatch, useSelector} from "react-redux";
import {useState} from "react";
import {postUpdated, selectPostById} from "./postSlice";
import {useHistory} from "react-router-dom";
import {useEditPostMutation, useGetPostQuery, useGetPostsQuery} from "../api/apiSlice";

export const EditPostForm = (match) => {
  const { postId } = match.match.params
  // const dispatch = useDispatch()
  // const post = useSelector(
  //   state => selectPostById(state, postId)
  // )

  const { data: post } = useGetPostQuery(postId)
  const [updatePost, { isLoading }] = useEditPostMutation()

  const [title, setTitle] = useState(post.title)
  const [content, setContent] = useState(post.content)

  const onTitleChanged = (e) => {
    setTitle(e.target.value)
  }

  const onContentChange = (e) => {
    setContent(e.target.value)
  }

  const history = useHistory()

  const onSavePostClicked = async () => {
    if (title && content) {
      // dispatch(postUpdated({ id: postId, title, content }))
      await updatePost({ id: postId, title, content })
      history.push(`/posts/${postId}`)
    }
  }

  return (
    <section>
      <h2>编辑文章</h2>
      <form action="">
        <label htmlFor="postTitle">文章标题：</label>
        <input
          type="text"
          id="postTitle"
          name="postTitle"
          placeholder="请输入标题"
          value={title}
          onChange={onTitleChanged}
        />

        <label htmlFor="postContent">内容：</label>
        <textarea
          id="postContent"
          name="postContent"
          value={content}
          onChange={onContentChange}
        />
      </form>

      <button
        type="button"
        onClick={onSavePostClicked}
      >
        save
      </button>
    </section>
  )
}
